package unionFind;

import java.util.HashSet;
import java.util.Set;

/**
 * 128. 最长连续序列
 */
public class P128 {
    public int longestConsecutive(int[] nums) {
        // 1. 初始化set
        Set<Integer> numSet = new HashSet<>();
        for (int num : nums) {
            numSet.add(num);
        }
        // 2. 遍历寻找最长长度
        int longestLen = 0;
        for (int num : numSet) {
            if (!numSet.contains(num - 1)) {
                int curNum = num;
                int curLen = 0;
                while (numSet.contains(curNum)) {
                    curNum++;
                    curLen++;
                }
                longestLen = Math.max(longestLen, curLen);
            }
        }
        return longestLen;
    }
}
